package com.ddstation.instrument_disinfect.controller;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

import javax.inject.Inject;
import javax.servlet.http.HttpSession;

import com.ddstation.common.service.DataDictionaryService;
import com.ddstation.common.service.InvsItemInstitutionService;
import com.ddstation.common.util.GeneralCheckUtil;
import com.ddstation.crm.menu.entity.DtInvsManageInstitutionMenuEntity;
import com.ddstation.crm.menu.service.MenuService;
import com.ddstation.exam.entity.DtHealthManageInstitutionGroupEntity;
import com.ddstation.exchange.service.DtHealthManageInstitutionGroupService;
import com.ddstation.instrument_disinfect.model.*;
import com.ddstation.master.entity.MaDataDictionaryEntity;
import com.ddstation.prescription_violate.model.InstitutionViolateResModel;
import com.ddstation.prescription_violate.model.ViolateDetailResModel;
import com.ddstation.util.getDateUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.ddstation.common.model.InvsCheckCommonSchParModel;
import com.ddstation.common.util.DateUtil;
import com.ddstation.crm.login.bean.SessionLoginData;
import com.ddstation.instrument_disinfect.service.InstrumentDisinfectService;
import com.ddstation.sewage.service.SewageService;

@Controller @Lazy
public class InstrumentDisinfectController {
	
	/**
	 * 仪器消毒数据查询页面 跳转
	 * 
	 * @param
	 * 
	 * @return
	 * @throws ParseException 
	 */
	@RequestMapping(value="invs_instrument_disinfect.do")
	public String wasteSeliveryInitEvent(
			Model model, HttpSession session) {

		// 从session获取基础数据
		SessionLoginData loginData = (SessionLoginData)session.getAttribute(SessionLoginData.KEY);
		if (loginData == null || loginData.getDoctor() == null || loginData.getInstitution() == null) {
			return "forward:login?timeout=true"; // session 过期
		}

        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
		// 获取当天
		Calendar cale = Calendar.getInstance();
		String lastday = format.format(cale.getTime());
		//取开始时间
		String firstday = getDateUtil.getFirstday(null);

        model.addAttribute("disinfectDtFrom", firstday); 	// 开始时间
		model.addAttribute("disinfectDtTo", lastday); 		// 当月的最后一天
		model.addAttribute("businessSubType",101);//初始显示设备消毒

		//一级医疗机构类别
		List<MaDataDictionaryEntity> typeFirstList = dataDictionaryService.getCodeList("institution_type_first");

		model.addAttribute("typeFirstList", typeFirstList);

		//获取二级菜单目录
		String firstMenuUrl = "invs_instrument_disinfect.do";
//		List<DtInvsManageInstitutionMenuEntity> secondMenus = menuService.getSecondMenus(loginData.getJurisdictionMenus(), firstMenuUrl);
		List<DtInvsManageInstitutionMenuEntity> secondMenus = menuService.getSecondMenus(loginData.getWorkbenchMenus(), firstMenuUrl);
		if(secondMenus == null){
			//无访问权限【跳转地址修改】
			return "forward:login?timeout=true";
		}
		model.addAttribute("secondMenus", secondMenus);

		return "pc/instrument_disinfect/instrument_disinfect";
	}

	/**
	 * 查询接口
	 * 
	 *
	 * @return
	 * @throws ParseException 
	 */
	@RequestMapping(value="invs_instrument_disinfect.do/load", method = RequestMethod.POST)
	public @ResponseBody Map<String, Object> loadInstrumentDisinfectListEvent(
			@RequestBody InvsCheckCommonSchParModel _in,
			HttpSession session) throws ParseException {

		Map<String, Object> ret = new HashMap<String, Object>();
		ret.put("errcode", -1);
		ret.put("errMsg", "系统出错，请稍后再试！");
		
		if ( _in.getBusinessSubType() == null) {
			ret.put("errMsg", "输入参数错误，请刷新页面后再试！");
			return ret;
		}
		
		// 日期check
		if ( StringUtils.isBlank(_in.getDtFrom()) || 
				StringUtils.isBlank(_in.getDtTo())){
			ret.put("errMsg", "没有输入查询日期！");
			return ret;
		}
		
        try {
        	 SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        	 format.parse(_in.getDtFrom());
        	 format.parse(_in.getDtTo());
		} catch (Exception e) {
			ret.put("errMsg", "输日期格式必须为：yyyy-MM-dd");
			return ret;
		}
		
        SessionLoginData loginData = (SessionLoginData)session.getAttribute(SessionLoginData.KEY );
        // session中卫监所的基础信息传入service
        _in.setInvsInstitutionId(loginData.getInstitution().getId());
        // 查询实施
        List<InstrumentDisinfectResModel> datalist = instrumentDisinfectService.searchInstrumentDisinfectList(_in);
		//查询全部父子机构信息
		Map<String, String> groupRelationship = getGroupRelationship();
		//定义重新组合集合
		List<InstrumentDisinfectResModel> comList=new ArrayList<>();
		Map<String, InstrumentDisinfectResModel> comMap = new HashMap<>();
		for(InstrumentDisinfectResModel data:datalist){
			//判断是否为子机构
			String belongId = groupRelationship.get(data.getInstitutionId());
			//父ID不存在则判断自己为父ID
			if(belongId == null){
				belongId = data.getInstitutionId();
			}else{
				//存在父ID剔除名称及机构ID
				data.setInstitutionName(null);
				data.setInstitutionId(null);
			}
			//获取当前ID数据
			InstrumentDisinfectResModel agoData = comMap.get(belongId);
			if(agoData == null){
				//数据不存在则添加数据
				comMap.put(belongId,data);
			}else{
				//数据存在累加数据
				Integer registryCnt = agoData.getRegistryCnt() + data.getRegistryCnt();
				Integer noAppealCnt = agoData.getNoAppealCnt() + data.getNoAppealCnt();
				agoData.setRegistryCnt(registryCnt);
				agoData.setNoAppealCnt(noAppealCnt);
				//替换名称为父ID对应名称
				if(data.getInstitutionName() != null){
					agoData.setInstitutionName(data.getInstitutionName());
				}
				//替换机构ID为父ID对应机构ID
				if(data.getInstitutionId() != null){
					agoData.setInstitutionId(data.getInstitutionId());
				}
				//取第一个规则
				if((agoData.getInvsInstrumentSet() == 0 || agoData.getInvsInstrumentSet() == null) && data.getInvsInstrumentSet() != 0){
					agoData.setInvsInstrumentSet(data.getInvsInstrumentSet());
				}
				//取第一个规则
				if((agoData.getInvsRoomSet() == 0 || agoData.getInvsRoomSet() == null) && data.getInvsRoomSet() != 0){
					agoData.setInvsRoomSet(data.getInvsRoomSet());
				}
				//存在一个状态为异常，则替换为异常
				if(data.getCheckSt() != 0){
					agoData.setCheckSt(-1);
				}
				//保存新累加的对象
				comMap.put(belongId,agoData);
			}
		}
		//遍历添加数据
		for (Map.Entry<String, InstrumentDisinfectResModel> entry : comMap.entrySet()) {
			//仅添加存在父机构数据
			if(entry.getValue() != null && entry.getValue().getInstitutionId() != null && entry.getValue().getInstitutionName() != null){
				comList.add(entry.getValue());
			}
		}
		ret.put("datalist",comList);
	
		ret.put("errcode", 0);
		ret.put("errMsg", "");
		return ret;
	}

	//获取整理好的父子关系对照数据
	public Map<String,String> getGroupRelationship(){
		Map<String, String> map = new HashMap<>();
		List<DtHealthManageInstitutionGroupEntity> groupList = dtHealthManageInstitutionGroupService.selectAll();
		//遍历数据将子机构ID作为key，父机构ID作为value
		for(DtHealthManageInstitutionGroupEntity group:groupList){
			map.put(group.getChildInstitutionId(),group.getParentInstitutionId());
		}
		return map;
	}


	/**
	 * 获取机构紫外线消毒情况
	 * @param dtInvsUltravioletResModel 查询参数
	 * @param session
	 * @return
	 */
	@RequestMapping(value="invs_instrument_disinfect.do/ultraviolet/load", method = RequestMethod.POST)
	public @ResponseBody Map<String, Object> loadInstrumentUltravioletListEvent(
			@RequestBody DtInvsUltravioletResModel dtInvsUltravioletResModel, HttpSession session) {
		Map<String, Object> ret = new HashMap<String, Object>();
		ret.put("errcode", -1);
		ret.put("errMsg", "系统出错，请稍后再试！");
		SessionLoginData loginData = (SessionLoginData)session.getAttribute(SessionLoginData.KEY );
		Integer status = dtInvsUltravioletResModel.getStatus() > -1 ? dtInvsUltravioletResModel.getStatus() : null;
		String name = StringUtils.isEmpty(dtInvsUltravioletResModel.getInstitutionName()) ? null : dtInvsUltravioletResModel.getInstitutionName();
		String institutionTypeFirst = StringUtils.isEmpty(dtInvsUltravioletResModel.getInstitutionTypeFirst()) ? "" : dtInvsUltravioletResModel.getInstitutionTypeFirst();
		List<DtInvsUltravioletResModel> invsUltraInstitutionList = instrumentDisinfectService.getInstitutionUltravioletByInvsInstitution(loginData.getInstitution().getId(),
				name, status , institutionTypeFirst);
		ret.put("institutionList",invsUltraInstitutionList);

		ret.put("errcode", 0);
		ret.put("errMsg", "");
		return ret;
	}

	/**
	 * 获取诊所所有紫外线灯的信息
	 * @param params 参数Map
	 * @return
	 */
	@RequestMapping(value="invs_instrument_disinfect.do/ultraviolet/load_detail", method = RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> invsUltraInstrumentLoadEvent(@RequestBody Map<String, Object> params) {
		Map<String, Object> retMap = new HashMap<String, Object>();
		retMap.put("errcode", -1);
		String institutionId = params.get("institutionId").toString();
		List<DtInvsInstitutionUltravioletInstrumentModel> instruments = instrumentDisinfectService.getUltravioletInstrumentsByInstitution(institutionId, null);
		if (!GeneralCheckUtil.isEmptyList(instruments)) {
			retMap.put("instruments", instruments);
		}
		List<UltravioletRecordDisplayModel> records = instrumentDisinfectService.getUltravioletRecordsByInstitution(institutionId);
		if (!GeneralCheckUtil.isEmptyList(records)) {
			retMap.put("records", records);
		}
		retMap.put("errcode", 0);
		return retMap;
	}

	/**
	 * 查询明细数据接口
	 * 
	 *
	 * @return
	 * @throws ParseException 
	 */
	@RequestMapping(value="invs_instrument_disinfect.do/load_detail", method = RequestMethod.POST)
	public @ResponseBody Map<String, Object> loadInstrumentDisinfectDetailEvent(
			@RequestBody InstrumentDisinfectDetailParModel _in,
			HttpSession session){

		Map<String, Object> ret = new HashMap<String, Object>();
		ret.put("errcode", -1);
		ret.put("errMsg", "系统出错，请稍后再试！");
		
		SessionLoginData loginData = (SessionLoginData)session.getAttribute(SessionLoginData.KEY );
		_in.setInvsInstitutionId(loginData.getInstitution().getId());
		// 输入参数check
		if ( StringUtils.isBlank(_in.getInstitutionId()) && 
				( StringUtils.isBlank(_in.getDtFrom()) && StringUtils.isBlank(_in.getDateYm()))
			){
			ret.put("errMsg", "系统出错，没有输入参数！");
			return ret;
		}
		
		if ( StringUtils.isNotBlank(_in.getDateYm())   ){
			String[] beginEndDate = DateUtil.getBeginEndDate(_in.getDateYm());
			if ( beginEndDate == null ){
				ret.put("errMsg", "系统出错，传入参数：年月错误！");
				return ret;
			}
			_in.setDtFrom(beginEndDate[0]);
			_in.setDtTo(beginEndDate[1]);
		}
		
		// 访问权限check(防止异常调用)
		if ( !sewageService.checkAccessAuthority(loginData.getInstitution().getId(),_in.getInstitutionId()) ){
			ret.put("errMsg", "没有访问权限！");
			return ret;
		}
		//查询机构全部子ID
		DtHealthManageInstitutionGroupEntity entity = new DtHealthManageInstitutionGroupEntity();
		entity.setParentInstitutionId(_in.getInstitutionId());
		List<DtHealthManageInstitutionGroupEntity> dtHealthManageInstitutionGroupList = dtHealthManageInstitutionGroupService.select(entity);

		//设置机构ID集合，必定存在父机构ID
		List<String> institutionIdList = new ArrayList<>();
		institutionIdList.add(_in.getInstitutionId());
		if(dtHealthManageInstitutionGroupList != null && dtHealthManageInstitutionGroupList.size() > 0){
			//存在子ID则全部加入in条件查询
			for(DtHealthManageInstitutionGroupEntity dtHealthManageInstitutionGroup:dtHealthManageInstitutionGroupList){
				institutionIdList.add(dtHealthManageInstitutionGroup.getChildInstitutionId());
			}
		}
		_in.setInstitutionIdList(institutionIdList);
		//去除原机构ID条件
		_in.setInstitutionId(null);
		//数据查询
		List<InstrumentDisinfectHeadResModel> datalist = instrumentDisinfectService.searchDetailList(_in);
		//替换展示 机构/科室 名称
		for(InstrumentDisinfectHeadResModel data:datalist){
			if(institutionIdList.get(0).equals(data.getInstitutionId())){
				data.setInstitutionShortName(data.getInstitutionName());
			}
		}
		// 查询实施
		ret.put("datalist",datalist);

		ret.put("errcode", 0);
		ret.put("errMsg", "");

		return ret;
	}
	
	/**
	 * 查询器械列表接口
	 * 
	 * @param institutionId  机构ID
	 * 
	 * @return
	 */
	@RequestMapping(value="invs_instrument_disinfect.do/load_instrument", method = RequestMethod.POST)
	public @ResponseBody Map<String, Object> loadInstrumentListEvent(
			@RequestParam String institutionId,
			@RequestParam Integer type,//1:器械 2：场所
			HttpSession session){

		Map<String, Object> ret = new HashMap<String, Object>();
		ret.put("errcode", -1);
		ret.put("errMsg", "系统出错，请稍后再试！");
		
		ret.put("instrumentList",instrumentDisinfectService.searchInstrumentList(institutionId,type));

		ret.put("errcode", 0);
		ret.put("errMsg", "");

		return ret;
	}


	/**
	 * 查询器械列表接口
	 *
	 * @param institutionId  机构ID
	 *
	 * @return
	 */
	@RequestMapping(value="invs_instrument_disinfect.do/load_source", method = RequestMethod.POST)
	public @ResponseBody Map<String, Object> loadsourceListEvent(
			@RequestParam String institutionId,
			@RequestParam Integer catalogId,
			HttpSession session){

		Map<String, Object> ret = new HashMap<String, Object>();
		ret.put("errcode", -1);
		ret.put("errMsg", "系统出错，请稍后再试！");

		ret.put("sourceList",invsItemInstitutionService.selectShowInvsItem(catalogId,institutionId));

		ret.put("errcode", 0);
		ret.put("errMsg", "");

		return ret;
	}

	@Inject private MenuService menuService;
	@Inject private InstrumentDisinfectService instrumentDisinfectService;
	@Inject private InvsItemInstitutionService invsItemInstitutionService;
	@Inject private SewageService sewageService;
	@Inject private DtHealthManageInstitutionGroupService dtHealthManageInstitutionGroupService;
	@Inject private DataDictionaryService dataDictionaryService;

}
